/*
 * How it works))
 * 
 * There are the right panel (it list of all users except the authorized), the Message Bar and the left panel
 * (users are added from the right panel, with which an authorized user begins the conversation).
 * When you click on the user name in the right panel, an alarm function that creates a new container with
 * the name of the user, the close button, the online indicator and field for the number of new messages
 * received from him. Next, create a container for messages in an array active_users adds the ID of the user.
 * Next function is activated activateDialog that hides a container with the current default user, class
 * atstive_user makes the current user and displays the active container messaging. Next getAllMessages
 * function works, which loads the container posts to user messages from the dialogue. At regular
 * intervals timerFunction works, which adds a new message to  containers for each conversation
 * (function getNewMessages), updates the online status from an authorized user and user IDs are in
 * the array active_users. sendMsg sends a new message to the server and add it to the container with
 * the messages of the current conversation. Close button removes the dialogue id solid active_users,
 * creates a button on the right panel and remove the button from the left panel. getNewMessages -
 * recursive function that increases the pointer to the array atcive_users.
 */

var active_users = new Array(); // users taking part in the dialogue
var count_of_new_msgs = new Array(); // count of new messages for active users
var current_user_id = null; // user's ID that is in dialogue now
var id_user = null; //id of authenticated user
var counter = 0;
var time_step = 5000;//default value

$(document).ready(function(){
    $('#sendMsgBtn').button();
    time_step = $('#chat_time_step').attr('msec');
    id_user = $('#authtorized_user_div').attr('id_user');
    setInterval(function() { timerFunction(); }, time_step);
});

function sendMsg()
{
    var textBox = $('#user_msg_text');
    
    $.get('addmessage/id_from/'+id_user+'/id_to/'+current_user_id+'/text/'+textBox.val(),
        function(){
            var div_msgs = document.getElementById('m'+current_user_id);
            var div_msg = document.createElement('div');
            var full_name = $('#authtorized_user_div').attr('full_name');
            var dateObj = new Date();
            var current_date = dateObj.getFullYear()+'-'+dateObj.getMonth()+'-'+
                               dateObj.getDay()+' '+dateObj.toLocaleTimeString();
            
            div_msg.innerHTML = full_name+'  '+current_date+'<br>'+textBox.val();
            div_msg.setAttribute('class', 'msg');
            div_msgs.appendChild(div_msg);
            div_msgs.scrollTop = div_msgs.scrollHeight;
            
            textBox.val('');
        }
    );
}

function removeMessages()
{
    var div_msgs = document.getElementById('msgs');
    while(div_msgs.firstChild) div_msgs.removeChild(div_msgs.firstChild);
}

function getAllMessages(id_user_with)
{
    $.get('getmessages/type/all/id_user/'+id_user+'/id_user_with/'+id_user_with,
        function(data){
            
            var msgs = eval(data);
            var full_name_user_with = $('#d'+id_user_with).attr('user_name');
            var full_name_user = $('#authtorized_user_div').attr('full_name');
            var full_name;

            var div_msgs = document.getElementById('m'+id_user_with);
            //var top = div_msgs.scrollTop;
            
            for(var key in msgs){
                var div_msg = document.createElement('div');
                
                if(msgs[key].id_from == id_user)
                    full_name = full_name_user;
                else full_name = full_name_user_with;
                
                div_msg.innerHTML = full_name+'  '+msgs[key].data+'<br>'+msgs[key].letter;
                div_msg.setAttribute('class', 'msg');
                div_msgs.appendChild(div_msg);
            }
            
            if(msgs != null)
                div_msgs.scrollTop = div_msgs.scrollHeight;
        }
    );
}

function getNewMessages()
{
    if(counter == active_users.length){
        counter = 0;
        return;
    }

    id_user_with = active_users[counter];
    counter++;

    $.get('getmessages/type/new/id_user/'+id_user+'/id_user_with/'+id_user_with,
        function(data){

            var msgs = eval(data);
            var full_name_user_with = $('#d'+id_user_with).attr('user_name');
            var full_name_user = $('#authtorized_user_div').attr('full_name');
            var full_name;
            var count = 0;

            var div_msgs = document.getElementById('m'+id_user_with);

            for(var key in msgs){
                var div_msg = document.createElement('div');

                if(msgs[key].id_from == id_user)
                    full_name = full_name_user;
                else full_name = full_name_user_with;

                div_msg.innerHTML = full_name+'  '+msgs[key].data+'<br>'+msgs[key].letter;
                div_msg.setAttribute('class', 'msg');
                div_msgs.appendChild(div_msg);

                count++;
            }

            if(msgs != null)
                div_msgs.scrollTop = div_msgs.scrollHeight;

            if(id_user_with != current_user_id){
                var index = active_users.indexOf(id_user_with);
                if(count_of_new_msgs[index] == null)
                    count_of_new_msgs[index] = 0;
                count_of_new_msgs[index] = parseInt(count_of_new_msgs[index]) + parseInt(count);
            }

            putCountOfNewMessagesToLabel(id_user_with);

            getNewMessages('new');
        }
        );
}

function activateDialog(id_div_dialog)
{    
    var dialog_button = $('#'+id_div_dialog);
    
    if(dialog_button.attr('class') == 'active_user')
        return;

    if(current_user_id != dialog_button.attr('id_user'))
        $('#m'+current_user_id).hide();
    
    current_user_id = dialog_button.attr('id_user');
    $('#m'+current_user_id).show();
    
    var sendBtn = $('#sendMsgBtn');
    sendBtn.attr('onclick', 'sendMsg()');
    
    var chat_dialogs = document.getElementById('chat_dialogs');
    for (var childItem in chat_dialogs.childNodes) {
        if (chat_dialogs.childNodes[childItem].nodeType == 1)
            chat_dialogs.childNodes[childItem].setAttribute('class', 'choose_user');
    }
    
    dialog_button.attr('class', 'active_user');
    
    var index = active_users.indexOf(current_user_id);
    count_of_new_msgs[index] = 0;
    
    putCountOfNewMessagesToLabel(current_user_id);
}

function addUserToDialog (user_div)
{
    var id_user_new = user_div.getAttribute('id_user');
    var user_dialog = document.getElementById('d'+id_user_new);

    if(user_dialog==null){
        var new_dialog = document.createElement('div');
        new_dialog.setAttribute('id', 'd'+id_user_new);
        new_dialog.setAttribute('id_user', id_user_new);
        new_dialog.setAttribute('user_name', user_div.getAttribute('user_name'));
        new_dialog.setAttribute('onclick', 'activateDialog("d'+id_user_new+'")');
        new_dialog.innerHTML = user_div.innerHTML;
        
        var new_close = document.createElement('div');
        new_close.setAttribute('class', 'close');
        new_close.innerHTML = 'x';
        new_close.setAttribute('onclick', 'removeDialog(this);');
        new_dialog.appendChild(new_close);
        
        var new_newMsgsLabel = document.createElement('div');
        new_newMsgsLabel.setAttribute('class', 'newmsgs');
        new_newMsgsLabel.setAttribute('id', 'n'+id_user_new);
        new_dialog.appendChild(new_newMsgsLabel);
        
        var new_msgs = document.createElement('div');
        new_msgs.setAttribute('id', 'm'+id_user_new);
        new_msgs.setAttribute('class', 'msgs');
        document.getElementById('msgs_panel').appendChild(new_msgs);
        
        user_div.parentNode.removeChild(user_div);
        
        var chat_dialogs = document.getElementById('chat_dialogs');
        for (var childItem in chat_dialogs.childNodes) {
            if (chat_dialogs.childNodes[childItem].nodeType == 1)
                chat_dialogs.childNodes[childItem].setAttribute('class', 'choose_user');
        }

        document.getElementById('chat_dialogs').appendChild(new_dialog);

        activateDialog('d'+id_user_new);
        
        new_dialog.setAttribute('class', 'active_user');
        
        getAllMessages(id_user_new);
        
        active_users.push(id_user_new);
        
    }else{
        document.getElementById('chat_dialogs').removeChild(user_dialog);
    }
}

function removeDialog(close_div)
{
    var id_user_to_remove = close_div.parentNode.getAttribute('id_user');
    var user_name = close_div.parentNode.getAttribute('user_name');
    var div_all_users = document.getElementById('all_users');
    var div_msgs = document.getElementById('m'+id_user_to_remove);
    var div_user_status = $('#status'+id_user_to_remove);
    var div_user_to_all = document.createElement('div');
    var div_status_to_all = document.createElement('div');
    
    div_user_to_all.setAttribute('class', 'choose_user');
    div_user_to_all.setAttribute('id_user', id_user_to_remove);
    div_user_to_all.setAttribute('onclick', 'addUserToDialog(this)');
    div_user_to_all.setAttribute('user_name', user_name);
    div_user_to_all.innerHTML = user_name;
    
    div_status_to_all.setAttribute('class', div_user_status.attr('class'));
    div_status_to_all.setAttribute('id', div_user_status.attr('id'));
    
    div_user_to_all.appendChild(div_status_to_all);
    
    div_all_users.appendChild(div_user_to_all);
    
    document.getElementById('chat_dialogs').removeChild(close_div.parentNode);
    
    div_msgs.parentNode.removeChild(div_msgs);
    
    var index = active_users.indexOf(id_user_to_remove);
    active_users.splice(index, 1);
    count_of_new_msgs.splice(index, 1);
    
    if(active_users.length)
        activateDialog('d'+active_users[0]);
    else{
        window.clearInterval();
        idInterval = null;
        $('#sendMsgBtn').attr('onclick', 'alert("Select user!")');
    }
}

function putCountOfNewMessagesToLabel(id_user_to_put)
{
    var label = $('#n'+id_user_to_put);
    
    var index = active_users.indexOf(id_user_to_put);
    count = parseInt(count_of_new_msgs[index]);

    if(count)
        label.text('('+count+')');
    else label.text('');
}

function timerFunction()
{
    /*
     * Refreshing user's statuses and reciving messages (one from another)
     */
    prolongationMyStatus();
}

function prolongationMyStatus()
{
    $.get('prolongationmystatus',
        function(){
            refreshingUsersStatuses();
        }
    );
}

function refreshingUsersStatuses()
{
    $.get('refreshingusersstatuses', //returns ids of online users
        function(json_ids){
            var ids = eval(json_ids);
            
            $('.status_on').attr('class', 'status_off');

            for(var key in ids)
            {
                $('#status'+ids[key].id).attr('class', 'status_on');
            }
            
            getNewMessages();
        }
    );
}